<!DOCTYPE html>
<html lang="en">
<head>
  <title>Vert.x for RxJS - Vert.x</title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">
  <meta content="Vert.x is a tool-kit for building reactive applications on the JVM." name="description">
  <link href="http://vertx.io/stylesheets/docs.css" media="screen" rel="stylesheet">
  <link href="http://vertx.io/stylesheets/font-awesome.min.css" media="screen" rel="stylesheet">
  <link href="http://vertx.io/javascripts/styles/rainbow.min.css" media="screen" rel="stylesheet">
  <!-- IE 6-8 support of HTML 5 elements -->
  <!--[if lt IE 9]>
  <script src="http://static.jboss.org/theme/js/libs/html5/pre3.6/html5.min.js"></script>
  <![endif]-->

  <link rel="apple-touch-icon" sizes="57x57" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-57x57.png">
  <link rel="apple-touch-icon" sizes="60x60" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-60x60.png">
  <link rel="apple-touch-icon" sizes="72x72" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-72x72.png">
  <link rel="apple-touch-icon" sizes="76x76" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-76x76.png">
  <link rel="apple-touch-icon" sizes="114x114" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-114x114.png">
  <link rel="apple-touch-icon" sizes="120x120" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-120x120.png">
  <link rel="apple-touch-icon" sizes="144x144" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-144x144.png">
  <link rel="apple-touch-icon" sizes="152x152" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-152x152.png">
  <link rel="apple-touch-icon" sizes="180x180" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-180x180.png">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/favicon-32x32.png" sizes="32x32">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/android-chrome-192x192.png" sizes="192x192">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/favicon-96x96.png" sizes="96x96">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/favicon-16x16.png" sizes="16x16">
  <link rel="manifest" href="http://vertx.io/assets/favicons/vertx-favicon-7/manifest.json">
  <link rel="mask-icon" href="http://vertx.io/assets/favicons/vertx-favicon-7/safari-pinned-tab.svg" color="#5bbad5">
  <meta name="msapplication-TileColor" content="#7d3194">
  <meta name="msapplication-TileImage" content="http://vertx.io/assets/favicons/vertx-favicon-7/mstile-144x144.png">
  <meta name="theme-color" content="#ffffff">

  <link href="http://fonts.googleapis.com/css?family=Ubuntu:400,500,700,400italic" rel="stylesheet" type="text/css">
  <link rel="alternate" type="application/rss+xml" title="RSS"
     href="http://vertx.io/feed.xml">
  <script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
    ga('create', 'UA-30144458-1', 'auto');
    ga('create', 'UA-71153120-1', 'auto', 'tracker');
    ga('send', 'pageview');
    ga('tracker.send', 'pageview');
  </script>
</head>
<body>

<a href="http://www.reactivemanifesto.org/" id="reactive-manifesto-banner">
  <img style="border: 0; position: fixed; right: 0; top:0; z-index: 9000"
    src="http://d379ifj7s9wntv.cloudfront.net/reactivemanifesto/images/ribbons/we-are-reactive-black-right.png">
</a>

<a id="skippy" class="sr-only sr-only-focusable" href="#content"><div class="container"><span class="skiplink-text">Skip to main content</span></div></a>

<header class="navbar navbar-default navbar-static-top" id="top" role="banner">
  <div class="container">
    <div class="navbar-header">
      <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#vertx-navbar-collapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a href="http://vertx.io/" class="navbar-brand"><img alt="Brand" src="http://vertx.io/assets/logo-sm.png"></a>
    </div>
    <nav class="collapse navbar-collapse" id="vertx-navbar-collapse">
      <ul class="nav navbar-nav navbar-right">
        <li><a href="http://vertx.io/download/">Download</a></li>
        <li><a href="http://vertx.io/docs/">Documentation</a></li>
        <li><a href="https://github.com/vert-x3/wiki/wiki">Wiki</a></li>
        <li><a href="http://vertx.io/community/">Community</a></li>
        <li><a href="http://vertx.io/materials/">Materials</a></li>
        <li><a href="http://vertx.io/blog/">Blog</a></li>        
      </ul>
    </nav>
  </div>
</header>



  <div class="page-header" id="content">
    <div class="container">
      <div class="row">
        <div class="col-sm-12">
          <h1>Vert.x for RxJS</h1>
          
        </div>
      </div>
    </div>
  </div>




<div id="content">
  <div class="container docs-content">
    <div class="row">
      <div class="col-sm-12 col-md-push-9 col-md-3 hidden-xs hidden-sm">
        <div id="sidebar" data-spy="affix">
          <ul class="sectlevel1">
<li><a href="#_read_stream_support">Read stream support</a></li>
<li><a href="#_handler_support">Handler support</a></li>
<li><a href="#_future_support">Future support</a></li>
<li><a href="#_scheduler_support">Scheduler support</a></li>
<li><a href="#_examples">Examples</a>
<ul class="sectlevel2">
<li><a href="#_eventbus_message_stream">EventBus message stream</a></li>
<li><a href="#_timers">Timers</a></li>
<li><a href="#_http_client_requests">Http client requests</a></li>
<li><a href="#_http_server_requests">Http server requests</a></li>
<li><a href="#_websocket_client">Websocket client</a></li>
<li><a href="#_websocket_server">Websocket server</a></li>
</ul>
</li>
</ul>
        </div>
      </div>
      <div class="col-sm-12 col-md-pull-3 col-md-9">
        <div class="toc hidden-md hidden-lg">
          <h2>Table of Contents</h2>
          <ul class="sectlevel1">
<li><a href="#_read_stream_support">Read stream support</a></li>
<li><a href="#_handler_support">Handler support</a></li>
<li><a href="#_future_support">Future support</a></li>
<li><a href="#_scheduler_support">Scheduler support</a></li>
<li><a href="#_examples">Examples</a>
<ul class="sectlevel2">
<li><a href="#_eventbus_message_stream">EventBus message stream</a></li>
<li><a href="#_timers">Timers</a></li>
<li><a href="#_http_client_requests">Http client requests</a></li>
<li><a href="#_http_server_requests">Http server requests</a></li>
<li><a href="#_websocket_client">Websocket client</a></li>
<li><a href="#_websocket_server">Websocket server</a></li>
</ul>
</li>
</ul>
        </div>
        <div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p><a href="https://github.com/Reactive-Extensions/RxJS">RxJS</a> is a popular library for composing asynchronous and event
based programs using observable sequences for the JavaScript.</p>
</div>
<div class="paragraph">
<p>Vert.x integrates naturally with RxJS, allowing to use observable wherever you can use streams or asynchronous results.</p>
</div>
<div class="paragraph">
<p>Vert.x for RxJS comes as an extension for RxJS:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">var Rx = require("rx.vertx");</code></pre>
</div>
</div>
<div class="paragraph">
<p>It provides the <code>Rx</code> object we need for creating <code>Observable</code>, or other kind of Rx objects.</p>
</div>
<div class="paragraph">
<p>If you are using Maven or Gradle, add the following dependency to the <em>dependencies</em> section of your build descriptor:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Maven (in your <code>pom.xml</code>):</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-xml" data-lang="xml">&lt;dependency&gt;
  &lt;groupId&gt;{maven-groupId}&lt;/groupId&gt;
  &lt;artifactId&gt;{maven-artifactId}&lt;/artifactId&gt;
  &lt;version&gt;{maven-version}&lt;/version&gt;
&lt;/dependency&gt;</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>Gradle (in your <code>build.gradle</code> file):</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-groovy" data-lang="groovy">compile {maven-groupId}:{maven-artifactId}:{maven-version}</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_read_stream_support">Read stream support</h2>
<div class="sectionbody">
<div class="paragraph">
<p>RxJS observable is a perfect match for Vert.x read streams : both provide a flow of items.
A read stream can be adapted to an observable with the <code>Rx.Observable.fromReadStream</code> function:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">var Rx = require("rx.vertx");
var fs = vertx.fileSystem();
fs.open("/data.txt", {}, function(result, err) {
  var file = result.result();
  var observable = Rx.Observable.fromReadStream(file);
  observable.forEach(function(data) {
    console.log("Read data: " + data.toString("UTF-8"));
  });
});</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_handler_support">Handler support</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The <code>rx.vertx</code> module provides an <code>observableHandler</code> function:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">var Rx = require("rx.vertx");
var observable = Rx.observableHandler();
observable.subscribe(
    function(evt) {
        // Got event
    }
);
vertx.setTimer(1000, observable.toHandler());</code></pre>
</div>
</div>
<div class="paragraph">
<p>Rx can also turn an existing Observer into an handler:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">var Rx = require("rx.vertx");

// Create an observer via the Rx api
var observer = Rx.Observer.create(
    function(evt) {
        // Got event
    }
);

// The rx.vertx extension augmented the observer with the toHandler method
var handler = observer.toHandler();
vertx.setTimer(1000, handler);</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_future_support">Future support</h2>
<div class="sectionbody">
<div class="paragraph">
<p>In Vert.x future objects are modelled as async result handlers and occur as last parameter of asynchronous methods.</p>
</div>
<div class="paragraph">
<p>The <code>rx.vertx</code> module provides an <code>observableFuture</code> function:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">var Rx = require("rx.vertx");

// Create an observable that is also an handler of async result
var observable = Rx.observableFuture();
observable.subscribe(
    function(server) {
        // Server is listening
    },
    function(err) {
        // Server could not start
    }
);

var server = vertx.createHttpServer({ "port":1234, "host":"localhost" });
server.listen(observable.toHandler());</code></pre>
</div>
</div>
<div class="paragraph">
<p>Rx can also turn an existing Observer into an future:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">var Rx = require("rx.vertx");

// Create an observer via the Rx api
var observer = Rx.Observer.create(
    function(evt) {
        // Got event
    }
);

// The rx.vertx extension augmented the observer with the toHandler method
var future = observer.toFuture();</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_scheduler_support">Scheduler support</h2>
<div class="sectionbody">
<div class="paragraph">
<p>RxJS relies on the default context method <em>timeout</em> and <em>interval</em> functions to schedule operations. The
vertx-js integration implements such functions providing an out of the box scheduler support.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_examples">Examples</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Let&#8217;s study now a few examples of using Vert.x with RxJava.</p>
</div>
<div class="sect2">
<h3 id="_eventbus_message_stream">EventBus message stream</h3>
<div class="paragraph">
<p>The event bus message consumer provides naturally an stream of messages:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">var Rx = require("rx.vertx");

var eb = vertx.eventBus();
var messageConsumer = eb.consumer("the-address");

// Create an observable from the message consumer
var observable = Rx.Observable.fromReadStream(messageConsumer);

// Subscribe to the observable
var subscription = observable.subscribe(
    function(msg) {
        // Got message
    });

// Unregisters the stream after 10 seconds
vertx.setTimer(10000, function() {
    subscription.dispose();
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>The message consumer provides a stream of messages. The <code>Message#body()</code> method gives access to a new
 stream of message bodies if needed:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">var Rx = require("rx.vertx");

var eb = vertx.eventBus();
var messageConsumer = eb.consumer("the-address");
var bodyConsumer = messageConsumer.bodyStream();

// Create an observable from the body consumer
var observable = Rx.Observable.fromReadStream(bodyConsumer);</code></pre>
</div>
</div>
<div class="paragraph">
<p>RxJS map/reduce composition style can be then be used:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">var Rx = require("rx.vertx");

var eb = vertx.eventBus();
var consumer = eb.consumer("heat-sensor").bodyStream();
var observable = Rx.Observable.fromReadStream(consumer);

observable.
    bufferWithTime(500).
    map(function (arr) { return arr.reduce(function (acc, x) { return acc + x; }, "") }).
    subscribe(
    function(heat) {
        console.log("Current heat is " + heat);
    });</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_timers">Timers</h3>
<div class="paragraph">
<p>Timer task can be created with <code>Vertx#timerStream(long)</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">var Rx = require("rx.vertx");
var timer = Rx.Observable.fromReadStream(vertx.timerStream(1000));
timer.subscribe(function(id) {
    console.log("Callback after 1 second");
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>Periodic task can be created with <code>Vertx#periodicStream(long)</code>:</p>
</div>
</div>
<div class="sect2">
<h3 id="_http_client_requests">Http client requests</h3>
<div class="paragraph">
<p>The HttpClientRequest provides a one shot callback with the
<code>http.HttpClientResponse</code> object. The observable reports a request failure.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">var Rx = require("rx.vertx");
var client = vertx.createHttpClient();
var req = client.request("GET", 8080, "localhost", "/the_uri");
var observable = Rx.Observable.fromReadStream(req);
observable.subscribe(function(resp) {
    // Process the response
}, function(err) {
    // Could not connect
});
req.end();</code></pre>
</div>
</div>
<div class="paragraph">
<p>The response can be processed as an stream of buffer:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">var Rx = require("rx.vertx");
var client = vertx.createHttpClient();
var req = client.request("GET", 8080, "localhost", "/the_uri");
Rx.Observable.fromReadStream(req).subscribe(function(resp) {
    var observable = Rx.Observable.fromReadStream(resp);
    observable.forEach(function(buffer) {
        // Process buffer
    });
});
req.end();</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_http_server_requests">Http server requests</h3>
<div class="paragraph">
<p>The <code>HttpServer#requestStream()</code> provides a callback for each incoming
request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">var Rx = require("rx.vertx");
var server = vertx.createHttpServer();
var requests = Rx.Observable.fromReadStream(server.requestStream());
requests.subscribe(function(request) {
    // Process the request
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>HttpServerRequest</code> can then be adapted to a buffer observable:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">Unresolved directive in index.adoc - include::http_server_request_observable.js[tags=example]</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_websocket_client">Websocket client</h3>
<div class="paragraph">
<p>The <code>HttpClient#websocketStream</code> provides a single callback when the websocket connects, otherwise a failure:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">var Rx = require("rx.vertx");
var client = vertx.createHttpClient();
var stream = client.websocketStream(8080, "localhost", "/the_uri");
Rx.Observable.fromReadStream(stream).
    subscribe(function (ws) {
        var observable = Rx.Observable.fromReadStream(ws);
        observable.forEach(function(buffer) {
            // Process message
        });

    });</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>WebSocket</code> can then be turned into an observable of buffer easily</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">var Rx = require("rx.vertx");
var client = vertx.createHttpClient();
var stream = client.websocketStream(8080, "localhost", "/the_uri");
var observable = Rx.Observable.fromReadStream(stream);
observable.subscribe(function(ws) {
    // Use the websocket
}, function(err) {
    // Could not connect
});</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_websocket_server">Websocket server</h3>
<div class="paragraph">
<p>The <code>HttpServer#websocketStream()</code> provides a callback for each incoming connection:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">var Rx = require("rx.vertx");
var server = vertx.createHttpServer();
var sockets = Rx.Observable.fromReadStream(server.websocketStream());
sockets.subscribe(function(ws) {
    // Process the web socket
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>ServerWebSocket</code> can be turned into a buffer observable easily:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">var Rx = require("rx.vertx");
var server = vertx.createHttpServer();
Rx.Observable.fromReadStream(server.websocketStream()).subscribe(function(ws) {
    var observable = Rx.Observable.fromReadStream(ws);
    observable.forEach(function(buffer) {
       // Process message
    });
});</code></pre>
</div>
</div>
</div>
</div>
</div>

        

        
          <div id="footer">
            <div id="footer-text">
              
                Last updated 2016-09-12 08:38:04 CEST
              
              
            </div>
          </div>
        
      </div>
    </div>
  </div>
</div>

<footer>
  <div class="container">
    <div class="row">
      <div class="col-xs-6 col-sm-3 col-md-3 col-lg-2">
        <h2>Vert.x</h2>
        <ul class="list-unstyled">
          <li><a href="http://vertx.io/">Home</a></li>
          <li><a href="http://vertx.io/download/">Download</a></li>
          <li><a href="http://vertx.io/docs/">Documentation</a></li>
          <li><a href="https://github.com/vert-x3/wiki/wiki">Wiki</a></li>
          <li><a href="http://vertx.io/blog/">Blog</a></li>
          <li><a href="http://vertx.io/vertx2/" class="vertx-2-link">Vert.x 2</a></li>
        </ul>
      </div>
      <div class="col-xs-6 col-sm-3 col-md-3 col-lg-2">
        <h2>Community</h2>
        <ul class="list-unstyled">
          <li><a href="http://vertx.io/community/">Help &amp; Contributors</a></li>
          <li><a href="http://vertx.io/materials/">Learning materials</a></li>
          <li><a href="https://groups.google.com/forum/?fromgroups#!forum/vertx">User Group</a></li>
          <li><a href="https://groups.google.com/forum/?fromgroups#!forum/vertx-dev">Developer Group</a></li>
        </ul>
      </div>

      <div class="col-xs-12 col-sm-6 col-lg-offset-2 col-md-6 copyright">
        <p>Vert.x is open source and dual licensed under the <a href="https://www.eclipse.org/org/documents/epl-v10.php">Eclipse Public License 1.0</a> and <a href="https://www.apache.org/licenses/LICENSE-2.0.html">Apache License 2.0</a>.</p>
        <p>This website is licensed under the <a href="http://creativecommons.org/licenses/by-sa/3.0/">CC BY-SA 3.0 License</a>.<br>
        Design by <a href="http://www.michel-kraemer.com">Michel Kr&auml;mer</a>. <a href="http://www.entypo.com">Entypo pictograms</a> by Daniel Bruce.</p>
        <div class="row">
          <div class="col-xs-12 col-lg-offset-1 col-md-5">
            <a href="http://eclipse.org">
            <img class="logo eclipse-logo" src="http://vertx.io/assets/eclipse_logo_grey_small.png" width="204" height="48">
            </a>
          </div>
          <div class="col-xs-12 col-md-offset-2 col-lg-offset-0 col-md-5">
            <a href="http://cloudbees.com">
            <img class="logo cloudbees-logo" src="http://vertx.io/assets/Button-Built-on-CB-1-grey.png" width="180" height="48">
           </a>
          </div>
          <div class="col-xs-12 col-md-offset-2 col-lg-offset-1 col-md-5 jprofiler">
            <a href="http://www.ej-technologies.com/products/jprofiler/overview.html"
            style="text-decoration:none">
            <img class="logo jprofiler-logo" src="http://vertx.io/assets/jprofiler-logo.png" width="48" height="48"><span class="jprofiler-logo">&nbsp; JPROFILER</span>
            </a>
          </div>
        </div>
      </div>
    </div>
  </div>
</footer>

<script src="http://static.jboss.org/theme/js/libs/jquery/jquery-1.9.1.min.js"></script>
<script src="http://vertx.io/javascripts/bootstrap.min.js"></script>
<script src="http://vertx.io/javascripts/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>



<script src="http://vertx.io/javascripts/sidebar.js"></script>


</body>
</html>
